package com.helen.ui.bottom;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.MessageListAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.MessageListEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseFragment;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.RecycleViewDivider;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.cache.converter.SerializableDiskConverter;
import com.zhouyou.http.cache.model.CacheMode;
import com.zhouyou.http.cache.model.CacheResult;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by yang on 2018/4/15.
 */

public class MessageFragment extends BaseFragment {
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    private List<MessageListEntity> list = new ArrayList();
    private View errorView;
    private MessageListAdapter messageListAdapter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        MyLog.d("yang", "MessageFragment");
        getToolbarTitle().setText(R.string.message);
        errorView = getActivity().getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) rvList.getParent(), false);
        messageListAdapter = new MessageListAdapter(R.layout.item_message_list, list);
        messageListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        swipeRefresh.setRefreshing(true);
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.appThemeColor));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_decoration));
        rvList.setAdapter(messageListAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(UserHelper.getInstance().isLogined()){
                    refresh();
                }
            }
        });


//        messageListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                MyLog.e("yang","99999999999999999999");
//                MessageListEntity messageListEntity = (MessageListEntity)adapter.getData().get(position);
//               Intent ti = new Intent(getActivity(), WebViewH5Activity.class);
//                ti.putExtra("id", messageListEntity.getId());
//                startActivity(ti);
//            }
//        });
        messageListAdapter.setOnItemDeleteListener(new MessageListAdapter.OnSetItemDeleteListener() {
            @Override
            public void setOnDeleteListener(MessageListEntity messageListEntity, int position) {
                deleteMessageApi(messageListEntity.getId() + "", position);
            }
        });
    }

    @Override
    protected void updateViews() {
        MyLog.e("yang","MessageFragment");
        if(UserHelper.getInstance().isLogined()){
            refresh();
        }

    }


    private void refresh() {
        messageListApi();
    }

    //    获取消息列表
    private void messageListApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId() + "");
        EasyHttp.post(Constants.API_JSONAPI_MESSAGELIST)
                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
                .cacheKey(Constants.API_JSONAPI_MESSAGELIST)
                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
                .execute(new SimpleCallBack<CacheResult<String>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                        swipeRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "消息列表失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(CacheResult<String> stringCacheResult) {
                        String data = PhoneUtils.checkResponseFlag2(getActivity(), stringCacheResult.data, TAG);
                        if (data != null) {
                            if (data != null && !data.equals("[]")) {
                                list = new Gson().fromJson(data, new TypeToken<List<MessageListEntity>>() {
                                }.getType());
                                messageListAdapter.setNewData(list);
                            } else {
                                messageListAdapter.setEmptyView(errorView);
                            }
                        }
                    }
                });
    }


    //    删除消息列表
    private void deleteMessageApi(String iid, final int position) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId());
        params.put("iid", iid);
        EasyHttp.post(Constants.API_JSONAPI_DELETEMESSAGE)
                .params(params)
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "删除消息失败==" + e.toString());
                        MToast.makeTextLong(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result, TAG);
                        if (data != null) {
                            MToast.makeTextLong(getActivity(), "删除成功").show();
                            messageListAdapter.remove(position);
                            messageListAdapter.notifyDataSetChanged();
                        }

                    }
                });

    }

}
